#include "input.h"

Input::Input()
{
	this->dInput = NULL;
	this->keyboard = NULL;
	this->mouse = NULL;
}

Input::~Input()
{
	//this->dInput = NULL;
	//this->keyboard = NULL;
	//this->mouse = NULL;
}

bool Input::Init(HINSTANCE hInstance, HWND hwnd, Vector2i screenSize)
{
	if(FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**) &dInput, NULL)))
		return false;

	if(FAILED(dInput->CreateDevice(GUID_SysKeyboard, &keyboard, NULL)))
		return false;

	if(FAILED(keyboard->SetDataFormat(&c_dfDIKeyboard)))
		return false;

	if(FAILED(keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE)))
		return false;

	if(FAILED(keyboard->Acquire()))
		return false;

	if(FAILED(dInput->CreateDevice(GUID_SysMouse, &mouse, NULL)))
		return false;

	if(FAILED(mouse->SetDataFormat(&c_dfDIMouse)))
		return false;

	if(FAILED(mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		return false;

	if(FAILED(mouse->Acquire()))
		return false;

	this->screenSize = screenSize;

	return true;
}

void Input::Destroy()
{
	if(mouse) {
		mouse->Unacquire();
		mouse->Release();
	}

	if(keyboard) {
		keyboard->Unacquire();
		keyboard->Release();
	}

	if(dInput)
		dInput->Release();
}

bool Input::PollInput()
{
	if(FAILED(keyboard->GetDeviceState(sizeof(keyboardState), (LPVOID) &keyboardState))) {
		keyboard->Acquire();
		return false;
	}

	if(FAILED(mouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID) &mouseState))) {
		mouse->Acquire();
		return false;
	}

	mousePos.x += mouseState.lX;
	mousePos.y += mouseState.lY;
	mouseDelta.x = mouseState.lX;
	mouseDelta.y = mouseState.lY;

	if(mousePos.x < 0)
		mousePos.x = 0;
	else if(mousePos.x > screenSize.x)
		mousePos.x = screenSize.x;
	if(mousePos.y < 0)
		mousePos.y = 0;
	else if(mousePos.y > screenSize.y)
		mousePos.y = screenSize.y;

	return true;
}

unsigned char* Input::GetKeyboardState()
{
	return this->keyboardState;
}

DIMOUSESTATE Input::GetMouseState()
{
	return this->mouseState;
}

Vector2i Input::GetMousePos()
{
	return this->mousePos;
}

Vector2i Input::GetMouseDelta()
{
	return this->mouseDelta;
}